﻿using CommonClass;
using I_SheepManagement.Domains;
using I_SheepManagement.Infrastructure.Interface;
using I_SheepManagement.Read.API.Application.Command;
using MediatR;

namespace I_eliminationManagement.Read.API.Application.CommandHandler
{
    public class EliminationManageReadCommandHandler : IRequestHandler<EliminationManageReadCommand, PageResult<EliminationManagement>>
    {
        private readonly IEliminationManagementRepository _eliminationManagementRepository;

        public EliminationManageReadCommandHandler(IEliminationManagementRepository eliminationManagementRepository)
        {
            _eliminationManagementRepository = eliminationManagementRepository;
        }

        public async Task<PageResult<EliminationManagement>> Handle(EliminationManageReadCommand request, CancellationToken cancellationToken)
        {
            var eliminationManage = _eliminationManagementRepository.GetByFuncListAsync(x => !x.IsDelete).Result.AsQueryable();

            if (!string.IsNullOrEmpty(request.EarNumber))
            {
                eliminationManage = eliminationManage.Where(a => a.EarNumber.Contains(request.EarNumber));
            }
            if (!string.IsNullOrEmpty(request.StartSheepElimination))
            {
                var startDate = DateTime.Parse(request.StartSheepElimination);
                eliminationManage = eliminationManage.Where(a => a.EliminationDate >= startDate);
            }
            if (!string.IsNullOrEmpty(request.EndSheepElimination))
            {
                var endDate = DateTime.Parse(request.EndSheepElimination);
                eliminationManage = eliminationManage.Where(a => a.EliminationDate <= endDate);
            }
            if (!string.IsNullOrEmpty(request.EliminationCause))
            {
                eliminationManage = eliminationManage.Where(a => a.EliminationCause.Equals(request.EliminationCause));
            }
            if (!string.IsNullOrEmpty(request.IsLeave))
            {
                eliminationManage = eliminationManage.Where(a => a.IsLeave.Equals(request.IsLeave));
            }

            var pageResult = new PageResult<EliminationManagement>();

            if (eliminationManage != null)
            {
                pageResult.TotalCount = eliminationManage.Count();
                pageResult.PageCount = (int)Math.Ceiling(pageResult.TotalCount * 1.0 / request.Size);
                pageResult.Datas = eliminationManage.OrderByDescending(a => a.Id).Skip(request.Size * (request.Index - 1)).Take(request.Size).ToList();
            }

            return pageResult;
        }
    }
}
